//
//  UIImage+TLImage.m
//
//
//  Created by tao故乡的云 on 16/4/8.
//  Copyright © 2016年 故乡的云. All rights reserved.
//

#import "UIImage+TLImage.h"

@implementation UIImage (TLImage)

+ (UIImage *)circleImageWithClipImage:(UIImage *)image borderWidth:(CGFloat)width borderColor:(UIColor *)color {
    
    CGFloat imageWH = image.size.width;
    
    // 1.开启图形上下文（位图)
    CGFloat contextWH = imageWH + width * 2; // 上下文宽高
    CGSize size = CGSizeMake(contextWH, contextWH);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    
    // 2.绘制圆环边框
    if (width) { // 需要边框,重绘path路径
        UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, contextWH, contextWH)];
        path.lineWidth = width;
        [color set];
        [path fill];
    }

    // 3.设置裁剪区域
    // 3.1 描述圆形裁剪区域路径
    UIBezierPath *path = path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(width, width, imageWH, imageWH)];;
    
    // 3.2 把路径设置为裁剪区域
    [path addClip];
    
    // 3.绘制图片
    [image drawInRect:CGRectMake(width, width, imageWH, imageWH)];
    
    // 5.保存新图片
    UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
    
    // 6.关闭位图上下文（优化性能）
    UIGraphicsEndImageContext();
    
    return newImg;
}

- (UIImage *)circleImageWithBorderWidth:(CGFloat)width borderColor:(UIColor *)color {
    return [UIImage circleImageWithClipImage:self borderWidth:width borderColor:color];
}


+ (UIImage *)imageWithScreenShot:(UIView *)view {
    
    // 1.开启位图上下文
    UIGraphicsBeginImageContext(view.bounds.size);
    
    // 2.获取上下文
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    
    // 3.把图片渲染到上下文
    [view.layer renderInContext:contextRef];
    
    // 4.获取截图
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    // 5.关闭上下文
    UIGraphicsEndImageContext();
    
    return image;
}

@end
